package org.example.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.example.constant.Header;
import org.example.domain.LoginUser;
import org.example.domain.response.ResponseResult;
import org.example.domain.response.ResponseResultEnum;
import org.example.utils.RedisCache;
import org.example.utils.ResponseUtils;
import org.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * token的验证过滤器
 */
@Component
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(Header.Token);
        log.info("token:" + token);
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        if(!TokenUtils.verify(token)){
            logger.error("token过时！");
            ResponseUtils.sendFailedString(response, ResponseResultEnum.AUTH_ERROR.getCode(), "token过时");
            return;
        }
        //如果有redis，可以从redis中查，可以减少查询数据库的次数，加快查询速度
        //使用redis后，可以实现登出逻辑删除redis中的值，这样登出后使用相同的token也登不进系统

        //从redis中获取用户信息
        String redisKey = "login:" + TokenUtils.getUserToken(token).getUserId();
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            logger.error("redis没有用户数据，用户未登录");
            ResponseUtils.sendFailedString(response,"用户未登录");
            return;
        }
        //过滤器添加授权信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);

    }
}
